package com.example.controller;

import com.example.aspect.annotation.AllowAnon;
import com.example.constant.RsaConstant;
import com.example.response.AjaxJson;
import com.example.service.RedisService;
import com.example.utils.RsaUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Api(tags = "RSA加密方法")
@RestController
@RequestMapping("/rsa")
public class RsaController {

    @Resource
    RedisService redisService;

    @ApiOperation("获取后台公钥")
    @GetMapping("/getPublicKey")
    @AllowAnon
    public AjaxJson getPublicKey() {
        String puk;
        try {
            puk = redisService.get(RsaConstant.RSA_PUBLIC_KEY).toString();
        } catch (Exception ignored) {
            initRsaKey();
            puk = redisService.get(RsaConstant.RSA_PUBLIC_KEY).toString();
        }
        return AjaxJson.ok(puk);
    }

    @AllowAnon
    @GetMapping("/update")
    @ApiOperation("刷新Rsa密钥")
    public AjaxJson updatePublicKey() {
        RsaUtil.setGenKeyPair();
        initRsaKey();
        return AjaxJson.ok();
    }

    @PostConstruct
    @AllowAnon
    @GetMapping("/init")
    @ApiOperation("初始化Rsa密钥")
    public AjaxJson initRsaKey() {
        String publicKey = RsaUtil.getPublicKey();
        String privateKey = RsaUtil.getPrivateKey();
        redisService.save(RsaConstant.RSA_PUBLIC_KEY, publicKey);
        redisService.save(RsaConstant.RSA_PRIVATE_KEY, privateKey);
        return AjaxJson.ok();
    }

}
